import { Button, Space, Popconfirm, message, type TableColumnsType, Modal } from "ant-design-vue";
import { formatTime } from "@/utils/common";
import { composeRuleApi } from "@/api/esArticle";
import GenerateArticleButton from "@/tsx/composeRule/GenerateArticleButton";
import { cloneDeep } from "@/utils/lodash";
import main from "@/stores/main";
import type { UserInfo } from "@/stores/main";
export type ContentNameKey =
    | "img_data"
    | "first_section_data"
    | "footer_section_data"
    | "main_body_section_data"
    | "reply_data"
    | "undergo_data"
    | "table_data"
    | "sentence_data";
// 配置这两个类型
export type ContentNameStyleKey = Exclude<ContentNameKey, "table_data" | "img_data">;

export type ContentNameStyleItem = {
    selectValues: Array<{
        title: string;
        key: SelectItemKey;
        options: SelectOption;
        value: string;
        componentStyle: Record<string, string>;
    }>;
    inputValues: Array<{
        title: string;
        key: InputItemKey;
        value: string | number;
        componentStyle: Record<string, string>;
        isNumber?: boolean;
    }>;
    isCustom: boolean;
    customStyle?: "";
};
export type ContentNameExistTitleItem = {
    title: ContentNameStyleItem;
    content: ContentNameStyleItem;
    isUseTitle: boolean;
    configIndex?: number;
};
// 内容名称Options
export function useContentNameOptions() {
    const contentNameOptions: SelectOption = [
        {
            label: "图片",
            value: "img_data"
        },
        {
            label: "首段",
            value: "first_section_data"
        },
        {
            label: "尾段",
            value: "footer_section_data"
        },
        {
            label: "段落",
            value: "main_body_section_data"
        },
        {
            label: "问答",
            value: "reply_data"
        },
        {
            label: "经历",
            value: "undergo_data"
        },
        {
            label: "句子",
            value: "sentence_data"
        },
        {
            label: "表格",
            value: "table_data"
        }
    ];
    return contentNameOptions;
}
// 样式Options
export function useStyleOptions() {
    const positionOptions: SelectOption = [
        { label: "居中", value: "center" },
        { label: "居左", value: "left" },
        { label: "居右", value: "right" }
    ];
    const fontOptions: SelectOption = [
        {
            label: "宋体",
            value: "宋体"
        },
        {
            label: "华文宋体",
            value: "华文宋体"
        },
        {
            label: "仿宋",
            value: "仿宋"
        },
        {
            label: "等线",
            value: "等线"
        },
        {
            label: "方正舒体",
            value: "方正舒体"
        },
        {
            label: "方正姚体",
            value: "方正姚体"
        },
        {
            label: "黑体",
            value: "黑体"
        },
        {
            label: "楷体",
            value: "楷体"
        },
        {
            label: "隶书",
            value: "隶书"
        },
        {
            label: "新宋体",
            value: "新宋体"
        },
        {
            label: "微软雅黑",
            value: "微软雅黑"
        },
        {
            label: "华文彩云",
            value: "华文彩云"
        },
        {
            label: "华文仿宋",
            value: "华文仿宋"
        },
        {
            label: "华文行楷",
            value: "华文行楷"
        },
        {
            label: "华文琥珀",
            value: "华文琥珀"
        },
        {
            label: "华文楷体",
            value: "华文楷体"
        },
        {
            label: "华文隶书",
            value: "华文隶书"
        },
        {
            label: "华文宋体",
            value: "华文宋体"
        },
        {
            label: "华文细黑",
            value: "华文细黑"
        },
        {
            label: "华文新魏",
            value: "华文新魏"
        },
        {
            label: "华文中宋",
            value: "华文中宋"
        }
    ];
    // 项目符号
    const itemCharOptions: SelectOption = [
        { label: "请选择", value: "" },
        { label: "1,2,3,4", value: "decimal" },
        { label: "01,02,03,04", value: "decimal-leading-zero" },
        { label: "a,b,c,d", value: "lower-alpha" },
        { label: "A,B,C,D", value: "upper-alpha" },
        { label: "I,II,III", value: "upper-roman" },
        { label: "实心圆点", value: "disc" },
        { label: "实心方块", value: "square" },
        { label: "空心圆点", value: "circle" }
    ];
    return { positionOptions, fontOptions, itemCharOptions };
}
export type ContentNameStyleObj = {
    first_section_data: ContentNameStyleItem;
    footer_section_data: ContentNameExistTitleItem;
    main_body_section_data: ContentNameExistTitleItem;
    reply_data: ContentNameExistTitleItem;
    undergo_data: ContentNameExistTitleItem;
    sentence_data: ContentNameExistTitleItem;
};
// 返回一个内容名称与样式对象的map
export function useContentNameStyleMap() {
    const { fontOptions, positionOptions, itemCharOptions } = useStyleOptions();

    const getFontSelectItem = createSelectItem("font-family", "", "字体", fontOptions, { width: "100px" });
    const getPositionSelectItem = createSelectItem("text-center", "", "对齐方式", positionOptions, { width: "70px" });
    const getItemCharSelectItem = createSelectItem("item_char", "", "项目符号", itemCharOptions, { width: "100px" });
    const getTagInputItem = createInputItem("tag", "p", "标签", { width: "60px" });
    const getColorInputItem = createInputItem("color", "#000111", "文字颜色", { width: "80px" });
    const getBackgroundColorInputItem = createInputItem("background-color", "#ffffff", "背景颜色", { width: "80px" });
    const getFontSizeInputItem = createInputItem("font-size", "14px", "字号", { width: "60px" });
    const getCountInputNumberItem = createInputItem("count", 3, "段落数量", { width: "60px" }, true);
    const obj: ContentNameStyleObj = {
        first_section_data: {
            selectValues: [getFontSelectItem(), getPositionSelectItem()],
            isCustom: false,
            customStyle: "",
            inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
        },
        footer_section_data: {
            title: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            content: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            isUseTitle: false
        },
        main_body_section_data: {
            title: {
                selectValues: [getFontSelectItem(), getPositionSelectItem(), getItemCharSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            content: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [
                    getTagInputItem(),
                    getColorInputItem(),
                    getBackgroundColorInputItem(),
                    getFontSizeInputItem(),
                    getCountInputNumberItem()
                ]
            },
            configIndex: 1,
            isUseTitle: false
        },
        reply_data: {
            title: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            content: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            isUseTitle: false
        },
        sentence_data: {
            title: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            content: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            isUseTitle: false
        },
        undergo_data: {
            title: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            content: {
                selectValues: [getFontSelectItem(), getPositionSelectItem()],
                customStyle: "",
                isCustom: false,
                inputValues: [getTagInputItem(), getColorInputItem(), getBackgroundColorInputItem(), getFontSizeInputItem()]
            },
            isUseTitle: false
        }
    };
    // 深拷贝一份 因为上面可能多个对象引用同一个地址 比如有标题项的
    return reactive(obj);
}
type errorDataItem = { label: string; index: string; host: string; keyword: string; msg: string };
export function useCreateTableColumns() {
    const isReloadRuleList = ref(false);
    // 当前修改的组合规则
    const currentUpdateComposeRule = ref<PostComposeRuleParmas | null>(null);
    // 是否展示规则组件
    const composeRuleComponentShow = ref(false);
    // 展示生成文章错误组件
    const showErrorGenerateArticle = ref(false);
    // 生成文章错误的data
    const errorDataList = ref<Array<errorDataItem>>([]);
    const columns: TableColumnsType = [
        {
            title: "规则名",
            dataIndex: "rule_name",
            key: "rule_name",
            align: "center"
        },
        {
            title: "ESIP",
            dataIndex: "generate_host",
            key: "generate_host",
            align: "center"
        },
        {
            title: "生成索引",
            dataIndex: "generate_index",
            key: "generate_index",
            align: "center"
        },
        {
            title: "网站组",
            dataIndex: "website_group_name",
            key: "website_group_name",
            align: "center"
        },
        {
            title: "行业类型",
            dataIndex: "trade_type_name",
            key: "trade_type_name",
            align: "center",
            width: 100
        },
        {
            title: "创建人",
            dataIndex: "create_name",
            key: "create_name",
            align: "center",
            width: 100
        },
        {
            title: "备注",
            dataIndex: "description",
            key: "description",
            align: "center",
            width: 100
        },
        {
            title: "创建时间",
            dataIndex: "create_time",
            key: "create_time",
            align: "center",
            customRender: (row) => h("div", {}, { default: () => formatTime(row.value) }),
            sorter: true
        }
    ];
    const defaultSlot = (str: string) => ({ default: () => str });
    const $store = main();
    const actions: TableColumnsType[0] = {
        title: "操作",
        dataIndex: "action",
        key: "action",
        align: "center",
        width: 300,
        fixed: "right",
        customRender: (row) => {
            // 删除规则按钮
            const deleteBtn = h(
                Popconfirm,
                {
                    title: "确认删除吗",
                    okText: "确认",
                    cancelText: "取消",
                    onConfirm() {
                        composeRuleApi({ id: row.record.id }, "delete")
                            .then((res) => commonThenCallback(res, "delete"))
                            .finally(() => {
                                isReloadRuleList.value = true;
                            });
                    }
                },
                {
                    default: () =>
                        h(
                            Button,
                            {
                                danger: true,
                                type: "link",
                                style: {
                                    padding: "4px 8px"
                                }
                            },
                            defaultSlot("删除")
                        )
                }
            );
            const updateBtn = h(
                Button,
                {
                    type: "link",
                    style: {
                        color: "#f0a020"
                    },
                    onClick() {
                        const newData = cloneDeep(row.record);
                        const wiatDeleteFields = ["trade_type_name", "website_group_name", "create_name", "create_time"];
                        for (const key in row.record) {
                            if (wiatDeleteFields.includes(key)) {
                                Reflect.deleteProperty(newData, key);
                            }
                        }
                        currentUpdateComposeRule.value = newData;
                        composeRuleComponentShow.value = true;
                    }
                },
                defaultSlot("修改规则")
            );
            // 公共的then回调
            const commonThenCallback = (res: any, type = "update") => {
                const s = type === "update" ? "修改" : "删除";
                if (res.data.code === 200) {
                    message.success(s + "成功!");
                } else {
                    message.error(s + "失败!");
                }
            };
            const generateArticleButton = h(GenerateArticleButton, { row });
            // 默认插槽
            return h(Space, {}, { default: () => [generateArticleButton, updateBtn, deleteBtn] });
        }
    };

    return {
        isReloadRuleList,
        currentUpdateComposeRule,
        composeRuleComponentShow,
        errorDataList,
        showErrorGenerateArticle,
        columns: [...columns, actions]
    };
}
type SourceComposeRuleList = Array<PostComposeRuleParmas & { id: number; create_time: string }>;
type TableData = Array<
    PostComposeRuleParmas & {
        id: number;
        create_time: string;
        user_name: string;
        website_group_name: string;
        trade_type_name: string;
    }
>;
export function useHandleTableData(
    data: SourceComposeRuleList,
    userOptions: Ref<SelectOption>,
    websiteGroupOptions: Ref<SelectOption>,
    websiteTypeOptions: Ref<SelectOption>
): TableData {
    const fieldMap = new Map([
        ["website_group_id", websiteGroupOptions],
        ["trade_type_id", websiteTypeOptions],
        ["create_id", userOptions]
    ]);
    data = data.map((item) => {
        Object.keys(item).forEach((key) => {
            const options = fieldMap.get(key);
            if (options) {
                const newKey = key.substring(0, key.indexOf("_id")) + "_name";
                // @ts-ignore
                item[newKey] = (options.value.find((selectItem) => selectItem.value == item[key]) || { label: "暂无" }).label;
            }
        });
        return item;
    });
    return data as TableData;
}

type InputItemKey = "color" | "tag" | "background-color" | "font-size" | "count";
function createInputItem(
    key: InputItemKey,
    value: string | number,
    title: string,
    componentStyle: Record<string, string>,
    isNumber: boolean = false
) {
    return function () {
        return {
            key,
            value,
            title,
            componentStyle,
            isNumber
        };
    };
}
type SelectItemKey = "font-family" | "text-center" | "title" | "item_char";
function createSelectItem(
    key: SelectItemKey,
    value: string,
    title: string,
    options: SelectOption,
    componentStyle: Record<string, string> = {}
) {
    return function () {
        return {
            title,
            key,
            options,
            value,
            componentStyle
        };
    };
}

export type { TableData };
